// -----------------------------------------------------------------------
//  <copyright file="User.cs" company="LiuliuSoft">
//      Copyright (c) 2022-2025 DaprPlus. All rights reserved.
//  </copyright>
//  <site>https://dapr.plus</site>
//  <last-editor>郭明锋</last-editor>
//  <last-date>2025/1/9 12:52</last-date>
// -----------------------------------------------------------------------

namespace DaprPlus.Identity.Domain.Entities;

/// <summary>
/// 实体类：用户
/// </summary>
[Description("用户")]
public class User : UserPlusBase<UserClaim, UserLogin, UserRole, UserToken>
{
    public User()
    {
        SecurityStamp = Guid.NewGuid().ToString();
    }

    /// <summary>
    /// 获取或设置 备注
    /// </summary>
    public string? Remark { get; set; }

    /// <summary>
    /// 获取或设置 用户扩展信息
    /// </summary>
    public virtual UserExtend UserExtend { get; set; } = null!;

    /// <summary>
    /// 获取或设置 所属部门
    /// </summary>
    public virtual List<Organization> Organizations { get; set; } = new();

    /// <summary>
    /// 获取或设置 登录日志
    /// </summary>
    public virtual List<LoginLog> LoginLogs { get; set; } = new();

    public void CreateUserExtend(string? ip)
    {
        if (Id == 0)
        {
            this.SetId();
        }
        UserExtend = new UserExtend()
        {
            Id = Id,
            RegisterIp = ip
        };
    }

    public void CreateLoginLog(string? ip, string? userAgent, string? remark)
    {
        var loginLog = new LoginLog()
        {
            UserId = Id,
            Ip = ip,
            UserAgent = userAgent,
            Remark = remark,
            CreatedTime = DateTime.Now
        };
        loginLog.SetId();
        LoginLogs.Add(loginLog);
    }

    public void SetLogoutLog(DateTime logoutTime)
    {
        var loginLog = LoginLogs.OrderByDescending(m => m.CreatedTime).FirstOrDefault();
        if (loginLog != null)
        {
            loginLog.LogoutTime = logoutTime;
        }
    }
}
